var ImageChooser = function(config){
	this.config = config;
}
ImageChooser.prototype = {    
    lookup : {},    
	show : function(el, callback){
		if(!this.win){
			this.initTemplates();			
			this.store = new Ext.data.JsonStore({
			    url: this.config.url,
				id : "id",
				root : "result",
				totalProperty : "rowCount",
				fields : ["name", "memo", "createTime", {name:'size', type: 'float'}, "keyword", "id","displayName", "relativePath", "modifyTime"],
			    listeners: {
			    	'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
			    }
			});
			this.store.load();			
			var formatSize = function(data){
		        if(data.size < 1024) {
		            return data.size + " bytes";
		        } else {
		            return (Math.round(((data.size*10) / 1024))/10) + " KB";
		        }
		    };			
			var formatData = function(data){
				data.url = data.relativePath.replace(/\\/g,   "/");
		    	data.shortName = Ext.util.Format.ellipsis(data.name,15);
		    	data.sizeString = Ext.util.Format.fileSize(data.size);
		    	data.dateString = data.modifyTime;
		    	this.lookup[data.name] = data;
		    	return data;
		    };			
		    this.view = new Ext.DataView({
				tpl: this.thumbTemplate,
				singleSelect: true,
				overClass:'x-view-over',
				itemSelector: 'div.thumb-wrap',
				emptyText : '<div style="padding:10px;">您还没有上传图片</div>',
				store: this.store,
				listeners: {
					'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
					'dblclick'       : {fn:this.doCallback, scope:this},
					'loadexception'  : {fn:this.onLoadException, scope:this},
					'beforeselect'   : {fn:function(view){
				        return view.store.getRange().length > 0;
				    }}
				},
				prepareData: formatData.createDelegate(this)
			});
			
			this.selectCombo = new Ext.form.ComboBox({
						xtype: 'combo',
				        typeAhead: true,
				        triggerAction: 'all',
				        width: 100,
				        editable: false,
				        mode: 'local',
				        displayField: 'desc',
				        valueField: 'name',
				        lazyInit: false,
				        value: 'name',
				        store: new Ext.data.SimpleStore({
					        fields: ['name', 'desc'],
					        data : [['name', '图片名称'],['size', '图片大小'],['modifyTime', '上传时间']]
					    }),
					    listeners: {
							'select': {fn:this.sortImages, scope:this}
					    }			
			});
			
			this.filter = new Ext.form.TextField({
						xtype: 'textfield',                    	
                    	selectOnFocus: true,
                    	width: 100,
                    	listeners: {
                    		'render': {fn:function(){
						    	this.filter.getEl().on('keyup', function(){
						    		this.filter();
						    	}, this, {buffer:500});
                    		}, scope:this}
                    	}
			});
			var cfg = {
		    	title: '请选择图片',
		    	
		    	layout: 'border',
				minWidth: 500,
				minHeight: 300,
				modal: true,
				closeAction: 'hide',
				border: false,
				items:[{
					
					region: 'center',
					autoScroll: true,
					items: this.view,
                    tbar:[{
                    	text: '关键字:'
                    },this.filter, ' ', '-', {
                    	text: '排序方式:'
                    }, this.selectCombo]
				},{
					
					region: 'east',
					split: true,
					width: 150,
					minWidth: 150,
					maxWidth: 250
				}],
				bbar : new Ext.PagingToolbar( {
					pageSize : 12,					
					store : this.store,
					displayInfo : true,
					displayMsg : '显示图片为{0}-{1}，共{2}张图片',
					emptyMsg : "没有可显示的图片！"
				}),
				buttons: [{
					id: 'ok-btn',
					text: '确定',
					handler: this.doCallback,
					scope: this
				},{
					text: '取消',
					handler: function(){ this.win.hide(); },
					scope: this
				}],
				keys: {
					key: 27, // Esc key
					handler: function(){ this.win.hide(); },
					scope: this
				}
			};
			Ext.apply(cfg, this.config);
		    this.win = new Ext.Window(cfg);
		    this.win.on('beforeshow',function(){
		    	this.store.reload();
		    },this)
		}
		
		this.reset();
	    this.win.show(el);
		this.callback = callback;
		this.animateTarget = el;
	},
	initTemplates : function(){
		this.thumbTemplate = new Ext.XTemplate(
			'<tpl for=".">',
				'<div class="thumb-wrap" id="{name}">',
				'<div class="thumb"><img src="../{url}" title="{name}" width="80px" height="110px" ></div>',
				'<span>{name}</span></div>',
			'</tpl>'
		);
		this.thumbTemplate.compile();		
		this.detailsTemplate = new Ext.XTemplate(
			'<div class="details">',
				'<tpl for=".">',
					'<img src="../{url}" width="110px" height="110px" ><div class="details-info"><br>',
					'<b>图片名称:</b>',
					'<span>{name}</span><br>',
					'<b>图片大小:</b>',
					'<span>{sizeString}</span><br>',
					'<b>上传时间:</b><br>',
					'<span>{dateString}</span></div>',
				'</tpl>',
			'</div>'
		);
		this.detailsTemplate.compile();
	},
	showDetails : function(){
	    var selNode = this.view.getSelectedNodes();
	    var detailEl = this.win.items.items[1].body;
		if(selNode && selNode.length > 0){
			selNode = selNode[0];
			Ext.getCmp('ok-btn').enable();
		    var data = this.lookup[selNode.id];
            detailEl.hide();
            this.detailsTemplate.overwrite(detailEl, data);
            detailEl.slideIn('l', {stopFx:true,duration:.2});
		}else{
		    Ext.getCmp('ok-btn').disable();
		    detailEl.update('');
		}
	},
	filter : function(){
		var filter = this.filter;
		this.view.store.filter('name', filter.getValue());
		this.view.select(0);
	},
	sortImages : function(){
		var v = this.selectCombo.getValue();
    	this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
    	this.view.select(0);
    },
	reset : function(){
		if(this.win.rendered){
			this.filter.reset();
			this.view.getEl().dom.scrollTop = 0;
		}
	    this.view.store.clearFilter();
		this.view.select(0);
	},
	doCallback : function(){
        var selNode = this.view.getSelectedNodes()[0];
		var callback = this.callback;
		var lookup = this.lookup;
		this.win.hide(this.animateTarget, function(){
            if(selNode && callback){
				var data = lookup[selNode.id];
				callback(data);
			}
		});
    },
	onLoadException : function(v,o){
	    this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>'); 
	}
};